<?php

// No direct access.
defined('_JEXEC') or die;

// Include dependancy of the main controllerform class
jimport('joomla.application.component.controllerform');

class NrmResearchControllerMigration extends JController
{

	public function getModel($name = 'ResearchProject', $prefix = 'NrmResearchModel') 
	{
		$model = parent::getModel($name, $prefix, array('ignore_request' => true));
		return $model;
	}
	//1
	public function migratePublicationOrganisationInvolved(){
		// Initialise variables.
		$app	= JFactory::getApplication();
		//$model	= $this->getModel('Publications');
		$log = JLog::getInstance();
		$log->addLogger(
				array(
						'text_file' => 'publication_organisation_migration.log.ini',
						'text_file_path' => 'logs'
				)
		);
		
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select('p.id');		
		$query->from('#__nrmresearch_publications AS p');
		
		// Get the users.
		$db->setQuery($query);
		$publications = $db->loadObjectList();
		
		//echo count($publications);die;
		foreach($publications as $publication){
			$this->updatePublication($publication->id);
		}
		die;
		return true;
	}

	private function updatePublication($id){			
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select('o.id, o.name');
		$query->from('#__nrmresearch__research_project__research_organisation AS ps');
		$query->join('RIGHT', '#__nrmresearch__research_organisation AS o ON ps.research_organisation_id = o.id');
		$query->where('ps.research_project_id='.$id);
		$db->setQuery((string) $query);
		$organisations = $db->loadObjectList();		
		//var_dump($organisations);die;
		if(count($organisations) == 1){
			$query = $db->getQuery(true);
			$query->update('#__nrmresearch_publications');
			$query->set('`lead_organisation`=  "'.$organisations[0]->name.'"');
			$query->where('id='.$id);
			$db->setQuery($query);
			$db->query();
		}
		else{
			foreach($organisations as $item){
				$query = $db->getQuery(true);
				$query->update('#__nrmresearch_publications');
				if(strpos($item->name, 'University of')!==FALSE)
					$query->set('`lead_organisation`=  "'.$item->name.'"');
				else
					$query->set('`partner_organisation_s`= case when trim(`partner_organisation_s`) = "" then "'.$item->name.'" ELSE concat(`partner_organisation_s`,",","'.$item->name.'") END');			
				$query->where('id='.$id);
				$db->setQuery($query);	
				$db->query();
				//echo $query;
			}		
		}
		//var_dump($organisations);die;
		//return $organisations;
	}
	

}
